#!/usr/bin/python
# -*- coding: utf-8 -*-

# (C) 2019, Chen Xiao <chen_xiao@bosc.cn>
# (C) 2019, Internal Use

import os
import re
import commands
# from ansible.module_utils.basic import *
from ansible.module_utils.basic import AnsibleModule

DOCUMENTATION = '''
---
module: linux_facts
version_added: "historical"
short_description: Gathers extra facts about remote hosts
requirements: [ ]
author:
    - "Chen Xiao"
options:
    filter:
        version_added: "1.1"
        description:
            - if supplied, only return facts that match this shell-style (fnmatch) wildcard.
        required: false
        default: '*'
'''

EXAMPLES = '''
---
# Display facts from all linux hosts
# ansible all -m linux_facts
# Display only facts regarding mysql version found by ansible on all linux hosts and output them.
# ansible all -m linux_facts -a 'filter=mysql_version'
'''


def mysql_version_get():
    try:
        (status, output) = commands.getstatusoutput('su - mysql -c "mysql -V" 2> /dev/null')
        if status == 0:
            results_str = output
            results_lt = re.split(r" |,", results_str)
            mysql_version = results_lt[5]
        else:
            (status, output) = commands.getstatusoutput('mysql -V 2> /dev/null')
            results_str = output
            results_lt = re.split(r" |,", results_str)
            mysql_version = results_lt[5]
    except Exception:
        mysql_version = ""

    return mysql_version


def sqlplus_version_get():
    try:
        results = os.popen('su - oracle -c "sqlplus -V"')
        results_str = results.read()
        results_lt = re.split(r" ", results_str)
        sqlplus_version = results_lt[2]
    except Exception:
        sqlplus_version = ""

    return sqlplus_version
    results.close()


def jboss_version_get():
    try:
        results = os.popen(
          'cat /upjas/*/modules/system/layers/base/org/jboss/as/product/upjas/dir/META-INF/MANIFEST.MF | grep JBoss-Product-Release-Version | sort -u'
        )
        results_str = results.read()
        results_lt = re.split(r":", results_str)
        jboss_version = results_lt[1].strip('\n')
    except Exception:
        jboss_version = ""

    return jboss_version
    results.close()


def user_get():
    try:
        (status, output) = commands.getstatusoutput("cat /etc/passwd")
        results_lt = output.split('\n')
        user_list = []
        for line in results_lt:
            sublist = line.split(':')
            del sublist[1]
            del sublist[3]
            user_list.append(sublist)
    except Exception:
        user_list = ""

    return user_list


def collect():
    facts_dict = {}
    try:
        facts_dict['mysql_version'] = mysql_version_get()
        facts_dict['sqlplus_version'] = sqlplus_version_get()
        facts_dict['jboss_version'] = jboss_version_get()
        facts_dict['user'] = user_get()
        # facts_dict['shell_get'] = shell_get()
    except Exception as e:
        print e
    finally:
        return facts_dict


def main():
    module = AnsibleModule(
        argument_spec=dict(
            filter=dict(default="*", required=False),
        ),
    )
    filter_spec = module.params['filter']

    try:
        facts = collect()
        rc = 0
    except Exception:
        rc = 1

    facts_dict = {}
    if rc == 0:
        if filter_spec == '*':
            facts_dict = {
                'linux_facts': facts,
                'changed': False,
                'rc': rc
            }
        else:
            facts_dict = {
                filter_spec: facts[filter_spec],
                'changed': False,
                'rc': rc
            }
        module.exit_json(**facts_dict)
    elif rc == 1:
        module.fail_json(msg="collect function errors happened")


if __name__ == '__main__':
    main()
